/*
 * @(#)WebdavLogin.java
 *
 * Copyright (c) 2004 DCIVision Ltd
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of DCIVision
 * Ltd ("Confidential Information").  You shall not disclose such Confidential
 * Information and shall use it only in accordance with the terms of the license
 * agreement you entered into with DCIVision Ltd.
 */
package com.dcivision.webdav;

/**
 * <p>Class Name:       WebdavLogin.java    </p>
 * <p>Description:      Webdav login .</p>
 * @author              Charlie 
 * @company             DCIVision Limited
 * @creation date       19/11/2004
 * @version             $Revision: 1.9.2.3 $
 */
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.slide.simple.authentication.SessionAuthenticationManager;

import com.dcivision.framework.Crypt;
import com.dcivision.framework.DataSourceFactory;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.SessionContainer;
import com.dcivision.framework.SystemParameterConstant;
import com.dcivision.framework.SystemParameterFactory;
import com.dcivision.framework.Utility;
import com.dcivision.ldap.core.LdapAuthenticationHandler;
import com.dcivision.user.bean.UserRecord;
import com.dcivision.user.dao.UserRecordDAObject;

/**
 * Reference implementation for the 
 * {@link org.apache.slide.simple.authentication.SessionAuthenticationManager}.
 * It simply grants access to any user remembering the password for later access
 * without it. A pair of the username and the password separated by a colon is 
 * returned as the session.
 */

public class WebdavLogin implements SessionAuthenticationManager {

    public static final String REVISION = "$Revision: 1.9.2.3 $";
    
    private Map fakeMap = new HashMap();

    protected Log log = LogFactory.getLog(this.getClass().getName());
    
    public Object getAuthenticationSession(String user) {
        UserRecord result = (UserRecord) fakeMap.get(user);
        return result;
    }

    public Object getAuthenticationSession(String user, String password) {
        UserRecord result=null;     
        result=getConnector(user,password);                 
        if(result!=null);       
        fakeMap.put(user, result);      
        return result;
    }

    public void closeAuthenticationSession(Object session) {
    }
    
    private UserRecord getConnector(String userName,String password){
        UserRecord result=null;
        Connection conn=null;
        boolean success=false;
        
        Crypt.encrypt(password, SystemParameterFactory.getSystemParameter(SystemParameterConstant.CRYPTO_SALT));

        SessionContainer sessionCtn = new SessionContainer();
        String loginMethod = SystemParameterFactory.getSystemParameter(SystemParameterConstant.LOGIN_METHOD);

        try {
          conn = DataSourceFactory.getConnection();           
          UserRecordDAObject userRecordDAO = new UserRecordDAObject(sessionCtn, conn);
          UserRecord userRecord = (UserRecord) userRecordDAO.getObjectByLoginName(userName, GlobalConstant.RECORD_STATUS_ACTIVE);
          
          // Check User Record ID = 0 for administrator account access, 
          // LDAP login doesn't support administrator account.
          if(userRecord!=null){
            if(userRecord.getID().intValue() == 0 
              || Utility.isEmpty(loginMethod) 
              || loginMethod.equals(GlobalConstant.LOGIN_METHOD_PARADM))
            {
              String encrptedPwd = Crypt.encrypt(password, SystemParameterFactory.getSystemParameter(SystemParameterConstant.CRYPTO_SALT));
              success=encrptedPwd.equals(userRecord.getLoginPwd());
            //LDAP login begin
            }else if(loginMethod.equals(GlobalConstant.LOGIN_METHOD_LDAP) || loginMethod.equals(GlobalConstant.LOGIN_METHOD_NTLM) ){
              LdapAuthenticationHandler ldapAuthentication=new LdapAuthenticationHandler();
              success=ldapAuthentication.login(userName,password);                    
            }
            //LDAP login end
          }          
          if(success){
            //set plain text password into the UserRecord bean for further authentication purpose
            userRecord.setLoginPwd(password);
            result = userRecord;  
          }

        }catch (Exception e) {
             log.error(e.getMessage());
        }finally{
            try {
              if(conn!=null) conn.close();    
            }
            catch (SQLException e) {
              throw new RuntimeException("error.unexpecte");
            }finally{
              conn=null;
            }
        }
        return result;         
     }       
}
